//从京东主页获取

const log = require('../../util/log')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = require('../chromeMng.20180824').client;

async function getJdItems(obj) {
  try {
    obj = obj || {}
    if (!obj.key) {
      return new Promise((resolve, reject) => {
        reject('缺少key')
      })
    }
    obj.key = obj.key.trim()
    log('getting jd items', obj)
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value == 'https://www.jd.com/') {
      return step2(obj)
    }
    Page.navigate({
      url: 'https://www.jd.com/'
    })
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step2(obj) {
  try {
    log('getting jd items step 2', obj)
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value.indexOf('https://search.jd.com/Search?') != -1) {
      return step3(obj)
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#key")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#key")[0].value'})
    if (result.value != obj.key) {
      await Runtime.evaluate({expression: 'document.querySelectorAll("#key")[0].value="' + obj.key + '"'})
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".button")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt > 1) {
      return new Promise((resolve, reject) => {
        reject('按钮多于1个')
      })
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll(".button")[0].click()'})
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step3(obj) {
  try {
    log('getting jd items step 3', obj)
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#key")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step3(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#key")[0].value'})
    if (result.value != obj.key) {
      await Runtime.evaluate({expression: 'document.querySelectorAll("#key")[0].value="' + obj.key + '"'})
      var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".button")'})
      var cnt = result.description.substring(9, result.description.length - 1)
      if (cnt > 1) {
        return new Promise((resolve, reject) => {
          reject('按钮多于1个')
        })
      }
      await Runtime.evaluate({expression: 'document.querySelectorAll(".button")[0].click()'})
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step3(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    return step4(obj)
  } catch (err) {
    log(err)
  }
}

async function step4(obj) {
  try {
    log('getting jd items step 4', obj)
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".gl-item")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step4(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var items = []
    for (var i = 0; i < cnt; i++) {
      var item = {}
      var prefix = 'document.querySelectorAll(".gl-item")[' + i + '].'
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].src'})
      if (result.value) {
        item.img = result.value
      } else {
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].attributes["data-lazy-img"].value'})
        if (result.value) {
          item.img = result.value
        } else {
          log(i, result)
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              step4(obj).then(result => {
                resolve(result)
              }, result => {
                reject(result)
              })
            }, 1000)
          })
        }
      }
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".p-name")[0].innerText'})
      if (!result.value) {
        continue
      }
      item.title = result.value
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".p-img>a")[0].href'})
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step4(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".p-price")[0].innerText'})
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step4(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.price = parseFloat(result.value.substring(1))
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".p-img a")[0].href'})
      item.link = result.value
      items.push(item)
    }
    return new Promise(resolve => {
      resolve(items)
    })
  } catch (err) {
    log(err)
  }
}

module.exports = getJdItems
